<?php
define('ROOT_PATH', realpath(dirname(__FILE__) . '/..'));
define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
    realpath(ROOT_PATH . '/library'),
    get_include_path(),
)));

require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance()->setFallbackAutoloader(true);
//require_once 'BKH/Config.php';

$getOpt = new Zend_Console_Getopt(array(
    'environemnt|e-s'  => 'Applicaton environment (development, testing, qc, etc)',
));
if ($getOpt->getOption('e')) {
    define('APPLICATION_ENV', $getOpt->getOption('e'));
} elseif (getenv('APPLICATION_ENV')) {
    define('APPLICATION_ENV', getenv('APPLICATION_ENV'));
} else {
    define('APPLICATION_ENV', 'development');
}
$config = Lua_Config::load(array('database'));
$dbConfig = $config['resources']['db'];
//var_dump($dbConfig);die;
try {
    $db = Zend_Db::factory($dbConfig['adapter'], $dbConfig['params']);
    if (in_array('_metadata', $db->listTables())) {
        $version = (int)$db->fetchOne('SELECT db_version FROM _metadata');
    } else {
        $version = 0;
    }
} catch (Exception $ex) {
    $version = 0;
}

$createDatabase = (0 == $version);
$version = sprintf("%03d", $version + 1);

$files = array();
foreach (new DirectoryIterator($dbConfig['dbScriptDir']) as $fileInfo) {
    if($fileInfo->isDot()) continue;
    $files[$fileInfo->getFilename()] = $fileInfo->getPathname();
}
ksort($files);

foreach ($files as $filename => $pathname) {
    if ($filename > $version) {
        $password = $dbConfig['params']['password'];
        if ($password) {
            $password = "-p{$password} ";
        }

        if ($createDatabase) {
            $cmd = "{$dbConfig['mysqlExec']} -u{$dbConfig['params']['username']} {$password} --default_character_set utf8 < {$pathname}";
            $createDatabase = false;
        } else {
            $cmd = "{$dbConfig['mysqlExec']} -u{$dbConfig['params']['username']} -D{$dbConfig['params']['dbname']} {$password} --default_character_set utf8 < {$pathname}";
        }
        echo "{$cmd}\n";
        $process = proc_open($cmd, array(
            0 => STDIN,
            1 => STDOUT,
            2 => array('pipe', 'w'),
        ), $pipes);
        echo stream_get_contents($pipes[2]);
        $returnValue = proc_close($process);
        if ($returnValue != 0) break;
    }
}
